package com.zzjson.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

import java.util.ArrayList;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2020 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.zk.curator</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2020年03月30日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class AclDemo {
	public CuratorFramework curatorFramework;

	public void init() {
		CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
		builder.connectString("116.62.221.6:2181");
		builder.retryPolicy(new RetryOneTime(1));
		curatorFramework = builder.build();
		curatorFramework.start();
		System.out.println("init success ~");
	}

	/**
	 * 基于digest来创建权限
	 *
	 * @throws Exception
	 */
	public void acl() throws Exception {
		ArrayList<ACL> acls = new ArrayList<>();
		//id里面存储的是客户端的身份信息
		ACL digest = new ACL(ZooDefs.Perms.READ | ZooDefs.Perms.WRITE,
				new Id("digest",
						DigestAuthenticationProvider.generateDigest("admin:admin")));

		acls.add(digest);
		curatorFramework.create().withMode(CreateMode.PERSISTENT).
				withACL(acls).forPath("/test/acl");
		System.out.println("acl success ~");
	}

	/**
	 * 已经创建的节点，修改权限
	 *
	 * @throws Exception
	 */
	public void acl2() throws Exception {
		ArrayList<ACL> acls = new ArrayList<>();
		//id里面存储的是客户端的身份信息
		ACL digest = new ACL(ZooDefs.Perms.DELETE,
				new Id("digest",
						DigestAuthenticationProvider.generateDigest("admin:admin")));

		acls.add(digest);
		curatorFramework.setACL().withACL(acls).forPath("/dd");
		System.out.println("acl success ~");
	}

	/**
	 * 已经创建的节点，修改权限
	 *
	 * @throws Exception
	 */
	public void aclGetData() throws Exception {
		ArrayList<ACL> acls = new ArrayList<>();
		//id里面存储的是客户端的身份信息
		ACL digest = new ACL(ZooDefs.Perms.DELETE,
				new Id("digest",
						DigestAuthenticationProvider.generateDigest("admin:admin")));

		acls.add(digest);
		byte[] bytes = curatorFramework.getData().forPath("/dd");
		System.out.println(new String(bytes));
	}

	public static void main(String[] args) throws Exception {
		AclDemo aclDemo = new AclDemo();
		aclDemo.init();
		aclDemo.aclGetData();

	}

}
